package com.example.sanguogameserver.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.sanguogameserver.entity.UserInfo;
import com.example.sanguogameserver.mapper.UserInfoMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sanguogameserver.request.TapLoginReq;
import com.example.sanguogameserver.request.UserLogin;
import com.example.sanguogameserver.request.UserRegister;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-03-05
 */
@Service
public class UserInfoService extends ServiceImpl<UserInfoMapper, UserInfo> implements IService<UserInfo> {



    public UserInfo register(UserRegister userRegister) {
        UserInfo oldUserInfo = getByAccount(userRegister.getAccount());
        Assert.isNull(oldUserInfo, "用户账号已存在");
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("萌新001");
        userInfo.setAccount(userRegister.getAccount());
        userInfo.setPassword(SecureUtil.md5(userRegister.getPassword()));
        userInfo.setCreateTime(LocalDateTime.now());
        save(userInfo);
        return userInfo;
    }

    public UserInfo getByAccount(String account) {
        return lambdaQuery()
                .eq(UserInfo::getAccount, account)
                .last("limit 1")
                .one();
    }
    public UserInfo getByOpenId(String openId) {
        return lambdaQuery()
                .eq(UserInfo::getOpenId, openId)
                .last("limit 1")
                .one();
    }

    public UserInfo login(UserLogin userLogin) {
        UserInfo dataUserInfo = getByAccount(userLogin.getAccount());
        Assert.notNull(dataUserInfo, "密码错误");
        String passwordMd5 = SecureUtil.md5(userLogin.getPassword());
        Assert.equals(passwordMd5, dataUserInfo.getPassword(), "密码错误");
        return dataUserInfo;
    }

    public UserInfo tapLogin(TapLoginReq tapLoginReq) {
        UserInfo userInfo = getByOpenId(tapLoginReq.getOpenId());
        if(userInfo==null){
            userInfo = new UserInfo();
            userInfo.setUserName(tapLoginReq.getUserName());
            userInfo.setOpenId(tapLoginReq.getOpenId());
            userInfo.setCreateTime(LocalDateTime.now());
            save(userInfo);
        }
        return userInfo;
    }
}
